import React, { useMemo, useRef } from "react";

import { helper } from "vendor/utils/T";
import ProBox from "vendor/components/pro-box";
import SkProTable, { TableType, IProTableRef } from "vendor/components/pro-table-native";
import { permission, EnumAuthKey } from "@/service/permission";
import { useThemeToken, getEnv } from "@/constants";

import { getDataAction, getCreateOrEdit, getFilterItems } from './proTableDriver';
import { RespDataType } from '../api';
import { useList } from './useList';

interface ListProps { }

const List: React.FC<ListProps> = () => {
  const { themeToken } = useThemeToken();
  const proTableRef = useRef<IProTableRef>();
  const columns = useMemo(() => getColumns(proTableRef), [proTableRef]);
  const { loading, initData } = useList();

  return <ProBox loading={loading}>
    <SkProTable
      ref={proTableRef}
      dataAction={getDataAction(proTableRef, initData.formatMenuData)}
      rowKey={"id"}
      theme={themeToken.proTableToken}
      headerProps={{
        operatorProps: {
          btnList: [
            // { innerType: "create", authKey: EnumAuthKey.sysRole.addButton },
            { innerType: "edit", authKey: EnumAuthKey.sysRole.editButton },
            { innerType: "delete", authKey: EnumAuthKey.sysRole.removeButton }
          ].filter((item) => permission.can(item.authKey)),
          createOrEditProps: {
            modalProps: {
              width: "50%"
            },
            CreateOrEditContent: getCreateOrEdit(initData.menuTree),
            getModalTitle: (rowKey) => rowKey ? "编辑角色" : "创建角色",
          },
        },
        filterProps: {
          maxWidth: "50%",
          filterItems: getFilterItems(),
        }
      }}
      contentProps={{
        tableProps: {
          columns,
        }
      }}
      onError={(msg) => console.error(msg)}
    />
  </ProBox>
}

export default List;

const getColumns = (_: React.MutableRefObject<IProTableRef>) => {
  const { roleAllowUserUseTypeList, adminRoleTypeList } = getEnv().globalConfig;
  const allowUserUseToInfo = helper.convertArrayToObj(roleAllowUserUseTypeList);
  const adminRoleTypeToInfo = helper.convertArrayToObj(adminRoleTypeList);

  const columns: TableType.ColumnsType<RespDataType.RoleItem> = [
    {
      title: '角色名称',
      dataIndex: 'name',
    },
    {
      title: '角色类型',
      dataIndex: 'type',
      render:(value) => adminRoleTypeToInfo[value]?.label ?? "-"
    },
    {
      title: '普通用户使用',
      dataIndex: 'allowUserUse',
      render:(value) => allowUserUseToInfo[value]?.label ?? "-"
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
    },
  ];

  return columns;
}
